package com.idcard.huashi;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.zysoft.function.ApiUtil;
import com.zysoft.function.HorizontalProgressBarWithNumber;
import com.zysoft.function.Stroage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class ProjectFragment extends Activity {

    private boolean show = false;
    private HashMap<String, Object> Uploadimg;
    private  ArrayList<JSONObject> PersonList;

    public static final int SUCCEED = 0;
    public static final int FAILE = 1;
    public static final int Dictionary_SUCCESSD =2;
    public static final int TEAM_SUCCESSD =3;
    public static final int OFFILNE_FAILE = 5;
    public static final int OFFILNE_TEAM_SUCCESSD = 4;
    public static final int OFFILNE_PERSON_SUCCESSD = 6;
    public static final int OFFILNE__EXIT_SUCCESSD = 7;
    public static final int ImageUrl_FAILE = 8;
    public static final int LOGINFO_SUCCEED = 66;
    public static final int LOGINF_FAILE = 77;
    public static final int ImageUrl_SUCCEED = 9;
    public static final int LogUrl_SUCCEED = 88;
    public static final int LogUrl_FAILE = 99;

    private TextView offline_data_submit;//离线提交数据
    private TextView offline_log;//日志上传
    private TextView update_data;//更新本地数据
    private TextView log_exit;//退出登录
    private TextView btn_center;//取消Alert
    private TextView Switch_project;//项目切换
    private TextView Staff_exit;//人员退场
    private TextView data_entry;//数据录入
    private TextView depart_data;//班组部门
    private TextView Power_off;//设备断电
    private TextView Refresh;//刷新
    private EditText person_card;
    private String flgid;

    public HorizontalProgressBarWithNumber mProgressBar;
    public static final int MSG_PROGRESS_UPDATE = 0x110;

    private Alert alert;
    private View view;
    private Stroage stroage;
    private ApiUtil apiUtil;
    private ListView project_list;
    private SimpleAdapter adapter;
    private HashMap<String, Object> person;
   private HashMap<String,Object> urlList;
   private Context mCtx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏 使用自定义标题栏;
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        mCtx = this;
        alert = new Alert();
        stroage = new Stroage();
        apiUtil = new ApiUtil();
        setContentView(R.layout.frament_project);
        person_card = findViewById(R.id.person_card);
        project_list = findViewById(R.id.project_list);
        View show = findViewById(R.id.img_btn);
        View back = findViewById(R.id.img_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mCtx,IdcardFragment.class);
                startActivity(intent);
                finish();
            }
        });
        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alert.ShowAlert();
            }
        });
        initEvent();
        apiUtil.ShowLoading("加载中...",mCtx);
        Ajax(apiUtil.ProjectInf,0);
    }

    public void initEvent(){
        //输入框时时获取值
        person_card.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void afterTextChanged(Editable editable) {
                Log.e("zysoft",person_card.getText().toString().trim());
                adapter.getFilter().filter(person_card.getText().toString().trim());
            }
        });
    }
    public void initView(){
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            try {
                JSONArray jsPerson = new JSONArray(PersonList);
                for (int i = 0; i <jsPerson.length(); i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("name", jsPerson.getJSONObject(i).getString("name"));
                    map.put("code", jsPerson.getJSONObject(i).getString("code"));
                    if(jsPerson.getJSONObject(i).getJSONObject("contractorCorp") != null){
                        map.put("corpCode", jsPerson.getJSONObject(i).getJSONObject("contractorCorp").getString("corpCode"));
                    }
                    mapList.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        adapter = new SimpleAdapter(mCtx,
                mapList,  R.layout.project_item,
                new String[]{"name", "code","corpCode"},
                new int[]{R.id.project_item, R.id.project_id,R.id.project_code});
        project_list.setAdapter(adapter);
        project_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                HashMap<String,Object> map = (HashMap<String,Object>) project_list.getItemAtPosition(i);
                Log.e("zysoft","你点击了"+map.toString());
                stroage.setName(map.get("name").toString(),mCtx);
                stroage.setCode(map.get("code").toString(),mCtx);//缓存项目code
                stroage.setProcode(map.get("corpCode").toString(),mCtx);
                Intent intent = new Intent(mCtx,IdcardFragment.class);
                startActivity(intent);
            }
        });
    }
    @SuppressLint("HandlerLeak")
    public final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCEED: {
                    apiUtil.HideLoading();
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.has("code") && (json.getInt("code") == 200)){
                            JSONObject js = json.getJSONObject("data");
                            PersonList = new ArrayList<JSONObject>();
                            if(js.getJSONArray("records").length() ==0){
                                apiUtil.ShowToast("暂无项目数据,请先在PC新建加项目");
                                return;
                            }
                            for(int i = 0; i<js.getJSONArray("records").length();i++){
                                PersonList.add(js.getJSONArray("records").getJSONObject(i));
                            }
                            initView();
                        }else {
                            apiUtil.ShowToast(json.getString("msg"));
                            return;
                        }
                    } catch (JSONException e) {
                        apiUtil.ShowToast("数据解析异常");
                    }
                    break;
                }
                case LOGINFO_SUCCEED:{
                    apiUtil.HideLoading();
                    try {
                        JSONObject oklog = new JSONObject(msg.obj.toString());
                        if(oklog.has("code") && (oklog.getInt("code")) == 200){
                            apiUtil.ShowToast("日志上传成功");
                        }else {
                            apiUtil.ShowToast(oklog.getString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Log.e("zysoft",msg.obj.toString());

                    apiUtil.ShowToast("日志文件上传成功");
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/temp.log");
                    if(file.exists()){
                        file.delete();
                    }
                    break;
                }
                case LOGINF_FAILE:{
                    apiUtil.HideLoading();
                    apiUtil.ShowToast(msg.obj.toString());
                    break;
                }
                case FAILE:{
                    Log.e("zysoft", msg.obj.toString());
                    apiUtil.HideLoading();
                    apiUtil.ShowToast(msg.obj.toString());
                    break;
                }
                case LogUrl_SUCCEED:{
                    Log.e("zysoft","日志上传成功"+msg.obj.toString());
                    try {
                        JSONObject log = new JSONObject(msg.obj.toString());
                        if(log.has("resultCode") && log.getInt("resultCode") == 200){
                            saveLogInfo(log.getJSONArray("resultData").getJSONObject(0).getString("attaUrl"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case LogUrl_FAILE:{
                    Log.e("zysoft","日志上传失败");
                    apiUtil.ShowToast(msg.obj.toString());
                    break;
                }
            }
        }
    };
    public void saveLogInfo(String log){
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(10,TimeUnit.SECONDS)//读取超时时间
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("projectCode",stroage.getCode(mCtx).toString())
                .add("deviceType","手持设备")//设备类型
                .add("deviceCode",apiUtil.infouid(mCtx))//设备编码
                .add("logDate",apiUtil.dateTime())//上传日期
                .add("logUrl",log)//日志文件地址
                .build();
        Request request = new Request.Builder()
                .url(apiUtil.LogUrl)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mHandler.sendMessage(mHandler.obtainMessage(LOGINFO_SUCCEED, response.body().string()));
            }
            @Override
            public void onFailure(Call call, IOException e) {
                if(e instanceof SocketTimeoutException){
                    mHandler.sendMessage(mHandler.obtainMessage(LOGINF_FAILE, "请求超时"));
                }else {
                    mHandler.sendMessage(mHandler.obtainMessage(LOGINF_FAILE, "连接异常"));
                }
            }
        });
    }
    private void Ajax(String url,final int i){
        OkHttpClient client = new OkHttpClient.Builder()//创建OkHttpClient对象。
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(10,TimeUnit.SECONDS)//读取超时时间
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("zysoft", "responseCode" +"   " + response.code() + "responseMessage" + response.message());
                if(i == 0){
                    mHandler.sendMessage(mHandler.obtainMessage(SUCCEED, response.body().string()));
                }else {
                    mHandler.sendMessage(mHandler.obtainMessage(Dictionary_SUCCESSD, response.body().string()));
                }
            }
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("zydoft",e.getMessage());
                if(e instanceof SocketTimeoutException){
                    mHandler.sendMessage(mHandler.obtainMessage(FAILE, "请求超时"));
                }else {
                    mHandler.sendMessage(mHandler.obtainMessage(FAILE, "连接异常"));
                }
            }
        });
    }
    public class Alert implements View.OnClickListener {

        Intent intent = new Intent(mCtx,IdcardFragment.class);

        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View show = inflater.inflate(R.layout.show_dialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
        Dialog dialog = builder.create();
        public void ShowAlert(){
            dialog.show();
            Window window = dialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            lp.width = display.getWidth();
            dialog.getWindow().setAttributes(lp);
            dialog.getWindow().setGravity(Gravity.BOTTOM);//可以设置显示的位置
            dialog.getWindow().setContentView(show);//自定义布局应该在这里添加，要在dialog.show()的后面
            dialog.setCanceledOnTouchOutside(true);
            offline_data_submit = show.findViewById(R.id.offline_data_submit);//离线提交
            update_data = show.findViewById(R.id.update_data);//更新本地数据
            offline_log = show.findViewById(R.id.offline_log);//日志上传
            Switch_project = show.findViewById(R.id.Switch_project);//切换项目
            Staff_exit = show.findViewById(R.id.Staff_exit);//人员退场
            log_exit = show.findViewById(R.id.log_exit);//退出登录
            data_entry = show.findViewById(R.id.data_entry);//进场数据录入
            depart_data = show.findViewById(R.id.depart_data);//班组部门
            Power_off = show.findViewById(R.id.Power_off);//设备断电
            btn_center = show.findViewById(R.id.btn_center);//取消
            Refresh = show.findViewById(R.id.Refresh);//刷新
            Refresh.setVisibility(View.VISIBLE);
            Refresh.setText("刷新项目列表");
            offline_data_submit.setVisibility(View.GONE);
            update_data.setVisibility(View.GONE);
            Staff_exit.setVisibility(View.GONE);
            data_entry.setVisibility(View.GONE);
            depart_data.setVisibility(View.GONE);
            Switch_project.setVisibility(View.GONE);
            Power_off.setVisibility(View.GONE);
            offline_log.setVisibility(View.VISIBLE);
            //监听事件
            offline_log.setOnClickListener(this);
            offline_data_submit.setOnClickListener(this);
            log_exit.setOnClickListener(this);
            Power_off.setOnClickListener(this);
            btn_center.setOnClickListener(this);
            Refresh.setOnClickListener(this);

        }
        public void HideAlert(){
            dialog.dismiss();
        }
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.offline_data_submit:
                    Log.e("zysoft","你点击了离线提交数据按钮");
                    HideAlert();
//                    SubmitData();
                    break;
                case R.id.offline_log:
                    //Log.e("zysoft","你点击了日志上传");
                    HideAlert();
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/log.log");
                    if(!file.exists()){
                        apiUtil.ShowToast("日志文件不存在");
                        return;
                    }
                    if(apiUtil.copyFile(Environment.getExternalStorageDirectory().getAbsolutePath()+"/log.log",Environment.getExternalStorageDirectory().getAbsolutePath()+"/temp.log")){
                        SubmitLog(Environment.getExternalStorageDirectory().getAbsolutePath()+"/temp.log");
                    }else {
                        apiUtil.ShowToast("查找日志文件失败");
                    }
                    break;
                case R.id.log_exit:
                    Log.e("zysoft","你点击了退出当前项目按钮");
                    HideAlert();
                    Intent intent = new Intent(mCtx,MainActivity.class);
                    startActivity(intent);
                    break;
                case R.id.Power_off:

                    HideAlert();
                    break;
                case R.id.btn_center:
                    Log.e("zysoft","你点击了取消按钮");
                    HideAlert();
                    break;
                case R.id.Refresh:
                    HideAlert();
                    apiUtil.ShowLoading("刷新中...",mCtx);
                    Ajax(apiUtil.ProjectInf,0);
                    break;
            }
        }
    }
    //日志上传
    public void SubmitLog(String url){
        File file = new File(url);
        OkHttpClient client = new OkHttpClient.Builder()//创建OkHttpClient对象。
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(10,TimeUnit.SECONDS)//读取超时时间
                .build();
        RequestBody img = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("upFile","log.log",img)
                .addFormDataPart("attaId","0")
                .addFormDataPart("commTreeId","0")
                .addFormDataPart("attaDomain","penetrate")
                .addFormDataPart("domainId","100")
                .build();
        Request request = new Request.Builder()
                .url(apiUtil.ImageUrl)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mHandler.sendMessage(mHandler.obtainMessage(LogUrl_SUCCEED, response.body().string()));
            }
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("zysoft", String.valueOf(e));
                if(e instanceof SocketTimeoutException){
                    mHandler.sendMessage(mHandler.obtainMessage(LogUrl_FAILE, "请求超时"));
                }else {
                    mHandler.sendMessage(mHandler.obtainMessage(LogUrl_FAILE,"连接异常"));

                }
            }
        });
    }
}
